<?php
class CNBlogsSDK
{

    /**
     * 公钥
     * @var mixed 
     */
    private $public_key;

    /**
     *
     * @var string 
     */
    public $client_id = '';

    /**
     *
     * @var string 
     */
    public $client_secret = '';

    /**
     *
     * @var string 
     */
    public $authorization;

    /**
     * 
     * @var sring 
     */
    public $host = 'https://api.cnblogs.com';

    /**
     * 加密后的用户名
     * @var strig 
     */
    public $username = '';

    /**
     * 加密后的密码
     * @var string 
     */
    public $password = '';

    /**
     * 
     * @param mixed $public_key  公钥
     * @param string $client_id client ID
     * @param sring $client_secret client secret
     */
    public function __construct($public_key, $client_id, $client_secret)
    {
        //打开证书
        $pu_key = openssl_pkey_get_public($public_key);
        if (false === $pu_key) {
            return '公钥错误!';
        }
        $this->public_key = $pu_key;
        $this->client_id = $client_id;
        $this->client_secret = $client_secret;
        $this->authorization = base64_encode($this->client_id . ':' . $this->client_secret);
    }

    /**
     * 公钥加密数据
     * @param string $data 加密的数据
     * @param mixed $public_key 公钥
     * @return boolean
     */
    public function rsaEncrypt($data)
    {
        //加密数据
        $encrypt_data = '';
        $rs = openssl_public_encrypt($data, $encrypt_data, $this->public_key, OPENSSL_PKCS1_PADDING);
        if (false === $rs) {
            return false;
        }

        return $encrypt_data;
    }

    /**
     * 设置用户名
     * @param string $username 用户名
     * @return string
     */
    public function setUsername($username)
    {
        $rs = $this->rsaEncrypt($username);
        if (false === $rs) {
            return '用户名设置失败!';
        }
        $this->username = $rs;
    }

    /**
     * 设置密码
     * @param string $password 密码
     * @return string
     */
    public function setPassword($password)
    {
        $rs = $this->rsaEncrypt($password);
        if (false === $rs) {
            return '密码设置失败!';
        }
        $this->password = $rs;
    }

    /**
     * 获取token
     */
    public function getToken($username, $password)
    {
        $this->setUsername($username);
        $this->setPassword($password);

        require_once 'httpclient.php';
        $http = new HttpClient($this->host);
        $http->setHeader("Content-Type", "application/x-www-form-urlencoded");
        $http->setHeader("Authorization", "Basic " . $this->authorization);
        $status_code = $http->post("/token", [
            "username" => base64_encode($this->username),
            "password" => base64_encode($this->password),
            'grant_type' => 'password'
        ]);

        if ($status_code != 200) {
            return false;
        }

        $response = json_decode($http->getBody(), true);

        if ($response == false) {
            return false;
        }

        return $response;
    }

}
